<template>
	<view class="page">
		<view class="listVue flex-between flex-wrap">
			<!-- 无数据显示 -->
			<view class="w100 flex-column align-center padding-column20 fixed-auto" v-if="isEmpty">
				<image src="https://ant-aiet.oss-cn-hangzhou.aliyuncs.com/assets/empty.png"
					style="width: 256rpx; height: 256rpx;"></image>
				<text style="color: #81868e;">暂无AI视频作品</text>
			</view>

			<view class="item" v-for="(item, index) in list" :key="index">
				<!-- 视频生成成功 -->
				<view class="videoVue relative" v-if="item.status === 2"
					@click.stop="$tools.router('../play', item.videoUrl)">
					<image :src="item.videoUrl + '?x-oss-process=video/snapshot,t_1,f_jpg,w_330,m_fast,ar_auto'"
						style="width: 330rpx;" mode="aspectFill"></image>
					<view class="contrast flex-center align-center absolute-center"
						@click.stop="toContrast(item.videoUrl, item.uploadVideoUrl)">
						<image src="../../static/contrast.png" style="width: 30rpx; height: 30rpx;"></image>
						<text style="color: #fff; font-size: 28rpx; padding-left: 10rpx;">对比效果</text>
					</view>
				</view>
				
				<!-- 视频生成中 -->
				<view class="videoVue relative" v-if="item.status === 1" style="background: rgba(244,244,244,0.5);">
					<image class="absolute-auto" style="margin-top: -20rpx; width: 120rpx;height: 120rpx;"
						object-fit="contain"
						src="https://aiet-file-center.oss-cn-hangzhou.aliyuncs.com/shuziren/audio/shalou40501.png">
					</image>
					<view class="wavy absolute-auto">
						<text style="--i:1">预</text>
						<text style="--i:2">计</text>
						<text style="--i:3">需</text>
						<text style="--i:4">要</text>
						<text style="--i:5">{{ videoData }}</text>
						<!-- 
						<text style="--i:5">3</text>
						<text style="--i:6">~</text>
						<text style="--i:7">5</text>
						 -->
						<text style="--i:8">分</text>
						<text style="--i:9">钟</text>
						<text class="u-margin-left-5" style="--i:10"> .</text>
						<text class="u-margin-left-5" style="--i:11"> .</text>
						<text class="u-margin-left-5" style="--i:12"> .</text>
					</view>
				</view>
			
				<!-- 视频生成失败 -->
				<view class="videoVue relative" v-if="item.status === 3" style="background: rgba(244,244,244,0.5);">
					<image class="absolute-auto" style="margin-top: -20rpx; width: 130rpx;height: 130rpx;"
						object-fit="contain"
						src="https://aiet-file-center.oss-cn-hangzhou.aliyuncs.com/shuziren/audio/jiazaishibai23626.png">
					</image>
					<view class="absolute-auto"
						style="margin-top: 50px; display: flex; justify-content: center; align-items: center;">
						<view style="margin-right: 5rpx;">生成失败</view>
						<view>
							<image src="https://aiet-file-center.oss-cn-hangzhou.aliyuncs.com/shuziren/audio/问号图标1663590.png"
								style="width: 36rpx;height: 36rpx;right: 100rpx;" @click="showFailureReason(item)"></image>
						</view>
					</view>
				</view>
				
				<!-- 待确认(音频已生成) -->
				<view class="videoVue relative" v-if="item.status === 4" style="background: rgba(244,244,244,0.5);">
					<image class="absolute-auto" style="margin-top: -20rpx; width: 130rpx;height: 130rpx;"
						src="../../static/wait.png">
					</image>
					<view class="absolute-auto"
						style="margin-top: 50px; display: flex; justify-content: center; align-items: center;">
						<view style="margin-right: 5rpx;">视频待确认</view>
					</view>
				</view>
				
				<view class="flex-between align-center padding-row20" style="background: white; border-radius: 0 0 12rpx 12rpx; height: 88rpx;">
					<view style="color: #000; font-size: 24rpx; padding-right: 10rpx;" class="flex-1 line-1">{{ item.name }}</view>
					<view v-if="item.videoUrl && item.status === 2" class="btn text-center"
						style="width: 100rpx; height: 52rpx; background: #FFA0A0; line-height: 52rpx; color: #fff; border-radius: 12rpx;"
						@click.stop="toOpration(item.id, item.videoUrl, item.uploadVideoUrl)">操作</view>
					<view v-if="item.status === 3 || item.status ===1" class="btn text-center"
						style="width: 100rpx; height: 52rpx; background: #FFA0A0; line-height: 52rpx; color: #fff; border-radius: 12rpx;"
						@click.stop="deleteStop(item.id)">
						删除
					</view>
					<view v-if="item.status === 4" class="btn text-center"
						style="width: 100rpx; height: 52rpx; background: #FFA0A0; line-height: 52rpx; color: #fff; border-radius: 12rpx;"
						@click="toPlay(item)">
						试听
					</view>
				</view>
			</view>
		</view>
		
		<u-action-sheet :list="actions" v-model="show" @click="handleClick"></u-action-sheet>
		
		
		<u-modal v-model="showFailureModal" :content="failureReason" confirm-color="#FFA0A0" :show-cancel-button="false"
			@confirm="showFailureModal = false"></u-modal>
			
		<!-- 音频试听弹框 -->
		<u-popup v-model="show50" mode="center" border-radius="12" @close="close">
			<view class="popVue">
				<view class="title text-center">音频试听</view>
				<view class="item flex align-center margin40">
					<view class="playBtn relative" @click="playTestFun(cloneSoundUrl)">
						<image src=""
							style="width: 44rpx; height: 44rpx" class="absolute-auto" v-if="!isTest">
						</image>
						<image src=""
							style="width: 44rpx; height: 44rpx" class="absolute-auto" v-else></image>
					</view>	
					<text class="padding-row20">点击左侧按钮播放音频</text>
				</view>
				<!-- <view class="notice" v-if="soundTime - videoDuration > 2">注意：检测到当前音频时长大于视频素材时长，有可能导致合成后的视频在某一刻出现不连贯的问题，请悉知。</view> -->
				<view class="notice">注意：确认生成视频将扣除 <text>{{points}}积分</text></view>
				<view class="btnVue flex-between margin50">
					<view class="btn" @click="startFun(1)">取消生成视频</view>
					<view class="btn" @click="startFun(0)">确定生成视频</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			list: [],
			isEmpty: true,
			pageNum: 0,
			pageSize: 8,
			isLastPage: false,
			oprationId: "",
			oprationUrl: "",
			oprationUrl2: "",
			show: false,
			actions: [{ text: "保存到相册" }, { text: "删除该视频" }, { text: "分享给好友" }],
			intervalId: null,
			videoData: "3~6",
			failureReason: '',
			showFailureModal: false,
			audioContext: null,
			show50: false,
			cloneSoundUrl: "",
			projectId: "",
			points: 0,
			isTest: false,
			videoDuration: 0,
			soundTime: 0,
		}
	},
	async onLoad() {
		await this.getList()
	},
	
	onUnload() {
		if(this.intervalId) {
			clearInterval(this.intervalId);
			this.intervalId = null
		}
		this.isTest = false
		if(this.audioContext) {
			this.audioContext.destroy();
			this.audioContext = null;
		}
	},
	
	onShow() {
		this.setIntervalFun()
	},
	
	onReachBottom() {
		if (this.isLastPage) return
		this.pageNum++
		this.getList()
	},
	
	// 分享
	onShareAppMessage() {
		// // 获取页面的路径
		// const targetPagePath = '/pages/mine/contrast';
		// // 构建带有参数的路径
		// const targetPageParams = `videoUrl=${encodeURIComponent(this.oprationUrl)}&uploadVideoUrl=${encodeURIComponent(this.oprationUrl2)}`;
		// // 构建跳转到首页的路径，并添加跳转参数
		// const sharePath = `/pages/index/index?redirectTo=${encodeURIComponent(targetPagePath)}&${targetPageParams}`;
		return {
			title: '小昭数字人', // 分享标题
			path: `/pages/index/index?videoUrl=${encodeURIComponent(this.oprationUrl)}&uploadVideoUrl=${encodeURIComponent(this.oprationUrl2)}`, // 分享路径
			imageUrl: 'https://aiet-file-center.oss-cn-hangzhou.aliyuncs.com/shuziren/image/211014382643522.png', // 分享图片的URL
			success: function (res) {
				console.log('分享成功', res);
			},
			fail: function (res) {
				console.log('分享失败', res);
			}
		};
	},
	methods: {
		close(){
			this.isTest = false
			if(this.audioContext) {
				this.audioContext.destroy();
				this.audioContext = null;
			}
		},
		setIntervalFun(){
			this.intervalId = setInterval(async () => {
				const ky = new Map();
				for (let i = 0; i < this.list.length; i++) {
					if (this.list[i].status === 1) {
						ky.set(this.list[i].id, i)
					}
				}
				if (ky.size < 1) {
					clearInterval(this.intervalId);
					this.intervalId = null
				} else {
					const arr = [...ky.keys()];
					const res = await this.$request("/shuziren/userVideo/roundRobinList", { ids: arr })
					res.data.forEach(value => {
						const data = Object.values(value)[0]
						if (data && data.status != 1) {
							if (data.status === 3) {
								that.$u.toast("0,积分已返还")
							}
							this.list[ky.get(Object.keys(value)[0])].status = data.status
							this.list[ky.get(Object.keys(value)[0])].videoUrl = data.videoUrl
							this.list[ky.get(Object.keys(value)[0])].uploadVideoUrl = data.uploadVideoUrl
						}
					})
				}
			}, 10000);
		},
		
		toOpration(id, videoUrl, uploadVideoUrl) {
			this.oprationId = id
			this.oprationUrl = videoUrl
			this.oprationUrl2 = uploadVideoUrl
			this.show = true
		},
		showFailureReason(item) {
			this.failureReason = item.failedCause;
			this.showFailureModal = true;
		},
		
		toPlay(item){
			this.show50 = true
			this.projectId = item.id
			this.cloneSoundUrl = item.cloneSoundUrl
			this.points = item.points
			// this.soundTime = item.soundTime
			// this.videoDuration = item.videoDuration
			console.log(this.projectId, this.cloneSoundUrl, this.soundTime, this.videoDuration)
		},
		
		// 试听音频
		playTestFun(){
			if(this.audioContext) {
				this.audioContext.destroy();
				this.audioContext = null;
				this.isTest = false
				return
			}
			this.audioContext = uni.createInnerAudioContext();
			this.audioContext.autoplay = true;
			this.audioContext.src = this.cloneSoundUrl;
			this.isTest = true
			this.audioContext.onPlay(() => {
				console.log("开始播放");
			});
			this.audioContext.onEnded(() => {
				console.log("播放结束");
				this.isTest = false
				this.audioContext.destroy();
				this.audioContext = null;
			});
		},
		
		// 确认/取消生成视频
		startFun(status){
			if(this.audioContext) {
				this.audioContext.destroy();
				this.audioContext = null;
				this.isTest = false
			}
			this.show50 = false
			uni.showLoading()
			this.$request("/shuziren/userVideo/nextStep", {
				id: this.projectId,
				status: status
			}).then(res=>{
				if(res.code===200) {
					uni.hideLoading()
					this.$u.toast(status===1 ? "已取消生成视频" : "开始生成视频")
					setTimeout(()=>{
						this.pageNum = 0
						this.list = []
						this.getList()
					}, 2000)
				}else{
					uni.hideLoading()
					this.$u.toast(res.msg)
				}
			})
		},
		
		
		// 保存到相册、删除视频、分享视频
		handleClick(e) {
			console.log('当前传递参数', e)
			switch (e) {
				// 保存到相册
				case 0:
					this.keepFun()
					break;
				// 删除视频
				case 1:
					this.deleteFun()
					break;
				// 分享视频
				case 2:
					this.onCustomShareButtonTap()
					break;
			}
		},

		// 查看对比
		toContrast(videoUrl, uploadVideoUrl) {
			uni.navigateTo({
				url: `./contrast?videoUrl=${videoUrl}&&uploadVideoUrl=${uploadVideoUrl}`
			})
		},
		
		// 分享
		onCustomShareButtonTap: function () {
			wx.showShareMenu({
				withShareTicket: true, // 是否使用带 shareTicket 的转发
				success: function (res) {
					console.log('显示分享菜单成功', res);
				},
				fail: function (res) {
					console.log('显示分享菜单失败', res);
				}
			});
		},

		// 保存
		keepFun() {
			let that = this
			uni.showLoading({
				title: "视频保存中..."
			})
			uni.downloadFile({
				url: that.oprationUrl,
				success(res) {
					uni.hideLoading()
					console.log('download success', res);
					uni.saveVideoToPhotosAlbum({
						filePath: res.tempFilePath,
						success: function () {
							that.$u.toast("保存成功")
							that.oprationId = ""
							console.log('save success');
						},
						fail(err) {
							console.log(err)
							console.log('save fail');
						}
					});
				},
				fail(err) {
					uni.hideLoading()
					that.$u.toast(err.errMsg)
				}
			})
		},
		
		// 删除
		deleteStop(id) {
			this.oprationId = id
			this.deleteFun()
		},
		
		// 删除
		async deleteFun() {
			const res = await this.$request("/shuziren/userVideo", { id: this.oprationId }, "DELETE")
			if (res.code === 200) {
				this.oprationId = ""
				this.$u.toast("删除成功")
				this.pageNum = 0
				this.list = []
				this.getList()
			}
		},

		// 获取用户AI作品
		async getList() {
			const res = await this.$request("/shuziren/userVideo/user", {
				pageNum: this.pageNum,
				pageSize: this.pageSize
			}, "GET")
			if (res.code === 200) {
				this.list = this.list.concat(res.data.content)
				this.isEmpty = this.list.length === 0
				this.isLastPage = res.data.page.number == res.data.page.totalPages - 1
				console.log("是否有下一页", this.isLastPage)
			}
			console.log("用户视频制作", this.userVideo)
		},
	}
}
</script>

<style lang="less" scoped>
.popVue {
	width: 650rpx;
	padding: 40rpx;
	.title {
		font-weight: 600;
		color: #000;
	}
	.notice {
		padding-top: 30rpx;
		color: #000;
		text {
			color: #FFA0A0;
			font-weight: 600;
		}
	}
	.item {
		width: 100%;
		height: 100rpx;
		border: 1rpx solid #ebeded;
		border-radius: 12rpx;
		.playBtn {
			width: 100rpx;
			height: 100rpx;
			background: #ebeded;
			border-radius: 12rpx 0 0 12rpx;
		}
	}
	.btnVue {
		width: 100%;
		height: 80rpx;
		.btn {
			width: 46%;
			height: 80rpx;
			text-align: center;
			line-height: 80rpx;
			border-radius: 12rpx;
		}
		.btn:nth-child(1) {
			background: #f5f5f5;
			color: #81868e;
		}
		.btn:nth-child(2) {
			background: #FFA0A0;
			color: #fff;
		}
	}
}
.listVue {
	width: 750rpx;
	padding: 30rpx;

	.item {
		width: 330rpx;
		height: 600rpx;
		background: #f5f5f5;
		box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(178, 178, 178, 0.25), inset 0rpx 8rpx 8rpx 0rpx rgba(255, 255, 255, 0.25);
		border-radius: 12rpx;
		margin-bottom: 30rpx;

		.contrast {
			width: 200rpx;
			height: 70rpx;
			background: rgba(0, 0, 0, 0.4);
			border-radius: 33rpx;
			bottom: 20rpx;
			color: #fff;
			font-size: 24rpx;
			text-align: center;
			line-height: 70rpx;
		}

		.videoVue {
			width: 330rpx;
			height: 520rpx;
			border-radius: 12rpx 12rpx 0 0;
			overflow: hidden;
		}
	}
}

.failed-overlay {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	/* 半透明背景 */
	display: flex;
	justify-content: center;
	align-items: center;
	color: #fff;
	font-size: 32rpx;
	z-index: 10;
	/* 确保覆盖在其他元素之上 */
}

.wavy {
	position: relative;
	margin-top: 100rpx;
	text-align: center;
	-webkit-box-reflect: below -12px linear-gradient(transparent, rgba(0, 0, 0, 0.2))
}

.wavy text {
	position: relative;
	display: inline-block;
	font-size: 26rpx;
	font-weight: bold;
	animation: animate 1.5s ease-in-out infinite;
	animation-delay: calc(.1s*var(--i))
}

@keyframes animate {
	0% {
		transform: translateY(0px)
	}

	20% {
		transform: translateY(-26rpx)
	}

	40%,
	100% {
		transform: translateY(0px)
	}
}
</style>
